package dryven.model.validation.validators;

import dryven.model.validation.ValidationFieldDescription;
import dryven.model.validation.ValidationFormValueCollection;
import dryven.model.validation.ValidationReporter;
import dryven.model.validation.Validator;
import dryven.request.controller.paramtransform.baseimpl.PrimitiveTypeBinder;

public class DefaultValidator implements Validator {

	private PrimitiveTypeBinder converter = new PrimitiveTypeBinder();
	public static final String INVALID_DATE_KEY = "dryven-invalid-primitive";
	public static final String INPUT_NOT_PRESENT_IN_REQUEST = "dryven-no-input";
	public static final String INPUT_REQUIRED = "dryven-required";
	
	@Override
	public void validate(ValidationFieldDescription desc,
			ValidationFormValueCollection form, ValidationReporter reporter) {
		Object value = null;
		String input = form.getValue(desc.getName());
		if(input==null) {
			reporter.reportError(desc.getName(), INPUT_NOT_PRESENT_IN_REQUEST, input);
		}
		if(input.trim().equals("") && desc.isRequired()) {
			reporter.reportError(desc.getName(), INPUT_REQUIRED, input);
		}
		try {
			value = converter.convertPrimitiveType(desc.getValueType(), input);
		} catch(Exception e) {
			reporter.reportError(desc.getName(), INVALID_DATE_KEY, input);
		}
		reporter.valueConverted(value);
	}

}
